package com.suneee.permission.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.suneee.permission.entity.Permission;

public class PermissionWrapUtil {
	
	public static String ROOT_FLAG = "null";
	
	public static Map<String,List<Permission>> treeWrap(List<Permission> list){
		Map<String,List<Permission>> map = new HashMap<>();
		for(int i = list.size() - 1;i >= 0;i--){
			Permission permission = list.get(i);
			String parentCode = permission.getParentCode();
			if(parentCode == null || "".equals(parentCode)){
				if(map.get(ROOT_FLAG) == null){
					map.put(ROOT_FLAG, new ArrayList<Permission>());
				}
				((List<Permission>)map.get(ROOT_FLAG)).add(permission);
			}
			else{
				if(map.get(parentCode) == null){
					map.put(parentCode, new ArrayList<Permission>());
				}
				((List<Permission>)map.get(parentCode)).add(permission);
			}
		}
		for(Permission permission : list){
			String code = permission.getCode();
			permission.setChildren(map.get(code));
		}
		return map;
	}
	
	public static Map<String,List<Permission>> enterpriseTreeWrap(List<Permission> list){
		Map<String,List<Permission>> map = new HashMap<>();
		for(Permission permission : list){
			String parentCode = permission.getParentCode();
			if(parentCode == null || "".equals(parentCode)){
				if(map.get(ROOT_FLAG) == null){
					map.put(ROOT_FLAG, new ArrayList<Permission>());
				}
				((List<Permission>)map.get(ROOT_FLAG)).add(permission);
			}
			else{
				if(map.get(parentCode) == null){
					map.put(parentCode, new ArrayList<Permission>());
				}
				((List<Permission>)map.get(parentCode)).add(permission);
			}
		}
		for(Permission permission : list){
			String code = permission.getCode();
			permission.setChildren(map.get(code));
		}
		return map;
	}

}
